<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="本文转自 eureka缓存细节以及生产环境的最佳配置 作者：http://bhsc881114.github.io/ eureka作为spring cloud微服务架构里的注册中心，是非常核心的一个组件，它避免了复杂的选主算法，架构比较简单，搭个demo也确实很快，但是如果要用于生产环境，还是得注意很多东西，尤其是下线延迟…">
<meta name="keywords" content="spring-cloud,微服务">
<meta property="og:type" content="article">
<meta property="og:title" content="(转)eureka缓存细节以及生产环境的最佳配置">
<meta property="og:url" content="http://www.saily.top/2018/04/14/spring-cloud-eureka/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="本文转自 eureka缓存细节以及生产环境的最佳配置 作者：http://bhsc881114.github.io/ eureka作为spring cloud微服务架构里的注册中心，是非常核心的一个组件，它避免了复杂的选主算法，架构比较简单，搭个demo也确实很快，但是如果要用于生产环境，还是得注意很多东西，尤其是下线延迟…">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://7xijc0.com1.z0.glb.clouddn.com/eureka-self.png">
<meta property="og:updated_time" content="2018-04-16T02:16:03.286Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="(转)eureka缓存细节以及生产环境的最佳配置">
<meta name="twitter:description" content="本文转自 eureka缓存细节以及生产环境的最佳配置 作者：http://bhsc881114.github.io/ eureka作为spring cloud微服务架构里的注册中心，是非常核心的一个组件，它避免了复杂的选主算法，架构比较简单，搭个demo也确实很快，但是如果要用于生产环境，还是得注意很多东西，尤其是下线延迟…">
<meta name="twitter:image" content="http://7xijc0.com1.z0.glb.clouddn.com/eureka-self.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/04/14/spring-cloud-eureka/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>(转)eureka缓存细节以及生产环境的最佳配置 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/04/14/spring-cloud-eureka/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">(转)eureka缓存细节以及生产环境的最佳配置
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-14T13:29:08+08:00">4月 14 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/spring/" itemprop="url" rel="index"><span itemprop="name">spring</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文转自 <a href="http://bhsc881114.github.io/2018/04/01/eureka%E7%BC%93%E5%AD%98%E7%BB%86%E8%8A%82%E4%BB%A5%E5%8F%8A%E7%94%9F%E4%BA%A7%E7%8E%AF%E5%A2%83%E7%9A%84%E6%9C%80%E4%BD%B3%E9%85%8D%E7%BD%AE/" target="_blank" rel="noopener">eureka缓存细节以及生产环境的最佳配置</a></p>
<p>作者：<a href="http://bhsc881114.github.io/" target="_blank" rel="noopener">http://bhsc881114.github.io/</a></p>
<p>eureka作为spring cloud微服务架构里的注册中心，是非常核心的一个组件，它避免了复杂的选主算法，架构比较简单，搭个demo也确实很快，但是如果要用于生产环境，还是得注意很多东西，尤其是下线延迟…<br><a id="more"></a></p>
<h2 id="服务获取中的缓存问题"><a href="#服务获取中的缓存问题" class="headerlink" title="服务获取中的缓存问题"></a>服务获取中的缓存问题</h2><p>本节的内容都是从这个issue翻译的：<a href="https://github.com/spring-cloud/spring-cloud-netflix/issues/373" target="_blank" rel="noopener">Documentation: changing Eureka renewal frequency WILL break the self-preservation feature of the server</a></p>
<h3 id="为什么修改client的默认心跳时间，会导致自我保护模式失效？"><a href="#为什么修改client的默认心跳时间，会导致自我保护模式失效？" class="headerlink" title="为什么修改client的默认心跳时间，会导致自我保护模式失效？"></a>为什么修改client的默认心跳时间，会导致自我保护模式失效？</h3><p>Eureka Service会认为客户端是以30s的频率来发送心跳的。服务端期望收到的最大心跳时间是：<br>n instances x 2(60s/30s) x threshold</p>
<p>如果是2个实例，Eureka会期望每分钟有：2 instances x 2 x 85% =3.4个心跳,也就是说需要3个心跳。<br>如果client的心跳改成15s，挂掉一个，另一个在1min内会发出4个心跳，而这时候的阈值还是3.4个，自我保护模式就失效了。<br>核心原因就是在Eureka Server计算期望心跳数的时候写死了每分钟的心跳间隔，即30秒，所以他永远会是*2(感觉像是新手写的代码啊啊啊 -_-)</p>
<p><img src="http://7xijc0.com1.z0.glb.clouddn.com/eureka-self.png" alt=""></p>
<p>还有一个参数可以调整，eureka.server.renewalThresholdUpdateIntervalMs，心跳阈值重新计算的周期，默认15分钟，可以改短一点，2min</p>
<h3 id="客户端首次注册时间为什么要30s？如何改进？"><a href="#客户端首次注册时间为什么要30s？如何改进？" class="headerlink" title="客户端首次注册时间为什么要30s？如何改进？"></a>客户端首次注册时间为什么要30s？如何改进？</h3><p>首次注册行为是和首次心跳绑定在一起的，首次心跳发送以后会收到not found的响应,client就知道还没注册过，client就会马上注册。首次心跳由参数<br>eureka.instance.leaseRenewalIntervalInSeconds控制的，默认30</p>
<p>可以通过eureka.client.initialInstanceInfoReplicationIntervalSeconds参数来加快首次注册的速度。他是控制首次改变实例状态（UP/DOWN ）的时间，启动的时候状态肯定是需要改变的，所以他可以用来加快首次注册速度，并且改变这个值不会影响到保护模式</p>
<p>另外如果你使用的是spring cloud eureka的话没首次注册延迟的问题，他会马上注册</p>
<h3 id="其他影响快速获取服务信息的因素"><a href="#其他影响快速获取服务信息的因素" class="headerlink" title="其他影响快速获取服务信息的因素"></a>其他影响快速获取服务信息的因素</h3><p><strong>【服务端缓存】</strong></p>
<p>因为服务端默认会有个read only response cache（下面会细说），每30秒更新一次(eureka.server.response-cache-update-interval-ms),所以可能注册了不是马上能看到（虽然通过rest api不能看到，但是你可以在web ui上看到，因为ui没有缓存）</p>
<p><strong>【客户端缓存】</strong></p>
<p>Eureka Client缓存的定期更新周期，他由eureka.client.registryFetchIntervalSeconds控制，默认30秒， 改成5秒</p>
<p><strong>【Ribbon缓存】</strong></p>
<p>如果你采用Ribbon来访问服务，那么这里会有个缓存（他的数据来源是本地Eureka Client缓存），他由ribbon. ServerListRefreshInterval控制，默认30秒， 改成2秒</p>
<h3 id="怎么更快的踢掉没有心跳的机器"><a href="#怎么更快的踢掉没有心跳的机器" class="headerlink" title="怎么更快的踢掉没有心跳的机器"></a>怎么更快的踢掉没有心跳的机器</h3><p>eureka.instance.leaseExpirationDurationInSeconds，这个值用来控制多久踢掉机器，默认是3个心跳周期，有点久，可以考虑改成2个，他不会影响到保护模式（如果开启自我保护模式，心跳间隔因为上面的bug不能改，只能改这个了 -_-）</p>
<hr>
<h2 id="服务端缓存细节"><a href="#服务端缓存细节" class="headerlink" title="服务端缓存细节"></a>服务端缓存细节</h2><p>Eureka内部的缓存分很多级，主要有registry、readWriterCacheMap、readOnlyCacheMap；另外还有一个维护最近180s增量的队列recentlyChangedQueue</p>
<h3 id="写操作"><a href="#写操作" class="headerlink" title="写操作"></a>写操作</h3><p>包括注册、取消注册等，都直接操作在registry上，同时也会更新recentlyChangedQueue和readWriterCacheMap</p>
<h3 id="读操作"><a href="#读操作" class="headerlink" title="读操作"></a>读操作</h3><p>读默认是从readOnlyCacheMap读取，读不到的话再从readWriterCacheMap，还没有再从registry</p>
<h3 id="滥用缓存的读操作"><a href="#滥用缓存的读操作" class="headerlink" title="滥用缓存的读操作"></a>滥用缓存的读操作</h3><p>这个读操作的三级缓存结构，非常让人困惑，registry已经是ConcurrentHashMap，纯内存操作，性能非常高了，为什么前面还要加两级缓存；readWriterCacheMap的数据是在写入以后responseCacheAutoExpirationInSeconds(默认180)秒内失效，readOnlyCacheMap则是一个定时任务，每responseCacheUpdateIntervalMs(默认30)秒从readWriterCacheMap获取最新数据</p>
<h3 id="去掉readOnlyCacheMap"><a href="#去掉readOnlyCacheMap" class="headerlink" title="去掉readOnlyCacheMap"></a>去掉readOnlyCacheMap</h3><p>从CAP理论上看，Eureka是一个AP系统，但是在C层面这么弱，就是因为各种无谓的缓存造成的，看了下readWriterCacheMap去掉比较难，但是readOnlyCacheMap有一个开关useReadOnlyResponseCache，果断关掉！！</p>
<hr>
<h2 id="Time-Lag"><a href="#Time-Lag" class="headerlink" title="Time Lag"></a>Time Lag</h2><p>最后再来看下Eureka wiki中提到的2min time lag问题，其实分多个角度看，不一定是2min</p>
<h3 id="服务正常上线-修改，最大可能会有120s滞后"><a href="#服务正常上线-修改，最大可能会有120s滞后" class="headerlink" title="服务正常上线/修改，最大可能会有120s滞后"></a>服务正常上线/修改，最大可能会有120s滞后</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- 30(首次注册 init registe) + 30(readOnlyCacheMap)+30(client fetch interval)+30(ribbon)=120</span><br><span class="line">- 如果是在Spring Cloud环境下使用这些组件(Eureka, Ribbon)，不会有首次注册30秒延迟的问题，服务启动后会马上注册,所以从注册到发现，最多可能是90s。</span><br></pre></td></tr></table></figure>
<h3 id="服务异常下线：最大可能会有270s滞后"><a href="#服务异常下线：最大可能会有270s滞后" class="headerlink" title="服务异常下线：最大可能会有270s滞后"></a>服务异常下线：最大可能会有270s滞后</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- 定时清理任务每eureka.server. evictionIntervalTimerInMs(默认60)执行一次清理任务</span><br><span class="line">- 每次清理任务会把90秒(3个心跳周期，eureka.instance.leaseExpirationDurationInSeconds)没收到心跳的踢除，但是根据官方的说法 ，因为代码实现的bug，这个时间其实是两倍，即180秒，也就是说如果一个客户端因为网络问题或者主机问题异常下线，可能会在180秒后才剔除</span><br><span class="line">- 读取端，因为readOnlyCacheMap以及客户端缓存的存在，可能会在30(readOnlyCacheMap)+30(client fetch interval)+30(ribbon)=90</span><br><span class="line">- 所以极端情况最终可能会是180+90=270</span><br></pre></td></tr></table></figure>
<h2 id="生产环境最佳配置"><a href="#生产环境最佳配置" class="headerlink" title="生产环境最佳配置"></a>生产环境最佳配置</h2><p>总结前面3点，经过梳理后，推荐的生产环境最佳配置如下：（可用于中小规模环境）：</p>
<h3 id="Eureka-Server端配置"><a href="#Eureka-Server端配置" class="headerlink" title="Eureka Server端配置"></a>Eureka Server端配置</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 中小规模下，自我保护模式坑比好处多，所以关闭它</span></span><br><span class="line">eureka.server.enableSelfPreservation=<span class="literal">false</span></span><br><span class="line"><span class="comment">## 心跳阈值计算周期，如果开启自我保护模式，可以改一下这个配置</span></span><br><span class="line"><span class="comment">## eureka.server.renewalThresholdUpdateIntervalMs=120000</span></span><br><span class="line"></span><br><span class="line"><span class="comment">## 主动失效检测间隔,配置成5秒</span></span><br><span class="line">eureka.server.evictionIntervalTimerInMs=5000</span><br><span class="line"></span><br><span class="line"><span class="comment">## 心跳间隔，5秒</span></span><br><span class="line">eureka.instance.leaseRenewalIntervalInSeconds=5</span><br><span class="line"><span class="comment">## 没有心跳的淘汰时间，10秒</span></span><br><span class="line">eureka.instance.leaseExpirationDurationInSeconds=10</span><br><span class="line"></span><br><span class="line"><span class="comment">## 禁用readOnlyCacheMap</span></span><br><span class="line">eureka.server. useReadOnlyResponseCache=<span class="literal">false</span></span><br></pre></td></tr></table></figure>
<h3 id="服务提供者和client配置"><a href="#服务提供者和client配置" class="headerlink" title="服务提供者和client配置"></a>服务提供者和client配置</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 心跳间隔，5秒</span></span><br><span class="line">eureka.instance.leaseRenewalIntervalInSeconds=5</span><br><span class="line"><span class="comment">## 没有心跳的淘汰时间，10秒</span></span><br><span class="line">eureka.instance.leaseExpirationDurationInSeconds=10</span><br><span class="line"></span><br><span class="line"><span class="comment"># 定时刷新本地缓存时间</span></span><br><span class="line">eureka.client.registryFetchIntervalSeconds=5</span><br><span class="line"><span class="comment"># ribbon缓存时间</span></span><br><span class="line">ribbon.ServerListRefreshInterval=2000</span><br></pre></td></tr></table></figure>
<p>改成上面配置后:</p>
<ul>
<li><p>正常上线下线客户端最大感知时间：eureka.client.registryFetchIntervalSeconds+ribbon. ServerListRefreshInterval = 7秒</p>
</li>
<li><p>异常下线客户端最大感知时间：<br>2*eureka.instance.leaseExpirationDurationInSeconds+<br>eureka.server.evictionIntervalTimerInMs+<br>eureka.client.registryFetchIntervalSeconds+<br>ribbon. ServerListRefreshInterval = 32</p>
</li>
</ul>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring-cloud/" rel="tag"># spring-cloud</a>
          
            <a href="/tags/微服务/" rel="tag"># 微服务</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/14/spring-cloud-green-blue/" rel="next" title="(转)Spring Cloud 实践-降级、限流、滚动、灰度、AB、金丝雀等等等等">
                <i class="fa fa-chevron-left"></i> (转)Spring Cloud 实践-降级、限流、滚动、灰度、AB、金丝雀等等等等
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/14/spring-cloud-gray/" rel="prev" title="Spring Cloud 不停机发布服务(0-downtime Blue/Green deployments)">
                Spring Cloud 不停机发布服务(0-downtime Blue/Green deployments) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#服务获取中的缓存问题"><span class="nav-number">1.</span> <span class="nav-text">服务获取中的缓存问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么修改client的默认心跳时间，会导致自我保护模式失效？"><span class="nav-number">1.1.</span> <span class="nav-text">为什么修改client的默认心跳时间，会导致自我保护模式失效？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#客户端首次注册时间为什么要30s？如何改进？"><span class="nav-number">1.2.</span> <span class="nav-text">客户端首次注册时间为什么要30s？如何改进？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其他影响快速获取服务信息的因素"><span class="nav-number">1.3.</span> <span class="nav-text">其他影响快速获取服务信息的因素</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#怎么更快的踢掉没有心跳的机器"><span class="nav-number">1.4.</span> <span class="nav-text">怎么更快的踢掉没有心跳的机器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端缓存细节"><span class="nav-number">2.</span> <span class="nav-text">服务端缓存细节</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#写操作"><span class="nav-number">2.1.</span> <span class="nav-text">写操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#读操作"><span class="nav-number">2.2.</span> <span class="nav-text">读操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#滥用缓存的读操作"><span class="nav-number">2.3.</span> <span class="nav-text">滥用缓存的读操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#去掉readOnlyCacheMap"><span class="nav-number">2.4.</span> <span class="nav-text">去掉readOnlyCacheMap</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Time-Lag"><span class="nav-number">3.</span> <span class="nav-text">Time Lag</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#服务正常上线-修改，最大可能会有120s滞后"><span class="nav-number">3.1.</span> <span class="nav-text">服务正常上线/修改，最大可能会有120s滞后</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务异常下线：最大可能会有270s滞后"><span class="nav-number">3.2.</span> <span class="nav-text">服务异常下线：最大可能会有270s滞后</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生产环境最佳配置"><span class="nav-number">4.</span> <span class="nav-text">生产环境最佳配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Eureka-Server端配置"><span class="nav-number">4.1.</span> <span class="nav-text">Eureka Server端配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务提供者和client配置"><span class="nav-number">4.2.</span> <span class="nav-text">服务提供者和client配置</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
